package com.qianfeng.qlm.handforireader.activity;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.text.Layout;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.lidroid.xutils.BitmapUtils;
import com.qianfeng.qlm.handforireader.R;
import com.qianfeng.qlm.handforireader.adapter.ViewPagerAdapter;
import com.qianfeng.qlm.handforireader.fragment.ActiveFragment;
import com.qianfeng.qlm.handforireader.fragment.CategoryFragment;
import com.qianfeng.qlm.handforireader.fragment.HotFragment;
import com.qianfeng.qlm.handforireader.fragment.NewFragment;
import com.qianfeng.qlm.handforireader.fragment.RecommendFragment;
import com.qianfeng.qlm.handforireader.util.Constant;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.LinkedList;


public class MainActivity extends FragmentActivity implements ViewPager.OnPageChangeListener, RadioGroup.OnCheckedChangeListener, View.OnClickListener {

    private ImageView mTableLine;
    private ViewPager mViewPager;
    private RadioGroup mRadioGroup;
    private int mScreen1_5;
    private SlidingMenu menu;
    private RequestQueue mRequestQueue;
    private String headImgUrl;
    private String activeImgUrl;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        context = this;

        mTableLine = (ImageView)findViewById(R.id.tabline);
        Display display = getWindow().getWindowManager().getDefaultDisplay();
        DisplayMetrics outMetrics = new DisplayMetrics();
        display.getMetrics(outMetrics);
        mScreen1_5 = outMetrics.widthPixels / 5;
        ViewGroup.LayoutParams lp = mTableLine.getLayoutParams();
        lp.width = mScreen1_5;
        mTableLine.setLayoutParams(lp);

        final ImageView mHeadImg = (ImageView) findViewById(R.id.head_img);

        mRequestQueue = Volley.newRequestQueue(this);



        JsonObjectRequest mJsonRequest = new JsonObjectRequest(Constant.HEADIMG,null,new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response != null) {
                        JSONArray head = response.getJSONArray("head");
                        if (head.length() >= 2){

                            headImgUrl = Constant.URL_SUFFIX + head.getJSONObject(0).getString("pic");
                            activeImgUrl = Constant.URL_SUFFIX + head.getJSONObject(1).getString("pic");

                            BitmapUtils bitmapUtils = new BitmapUtils(context);
                            bitmapUtils.configDefaultLoadingImage(R.mipmap.remimg);
                            bitmapUtils.display(mHeadImg,headImgUrl);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        },new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });



        mRequestQueue.add(mJsonRequest);




        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        mViewPager.setOffscreenPageLimit(5);

        LinkedList<Fragment> fragments = new LinkedList<>();

        fragments.add(new RecommendFragment());
        fragments.add(new CategoryFragment());
        fragments.add(new NewFragment());
        fragments.add(new HotFragment());
        fragments.add(new ActiveFragment());

        ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), fragments);
        mViewPager.setAdapter(pagerAdapter);

        mViewPager.setOnPageChangeListener(this);

        mRadioGroup = (RadioGroup) findViewById(R.id.radio_group);
        mRadioGroup.setOnCheckedChangeListener(this);
        RadioButton childAt = (RadioButton) mRadioGroup.getChildAt(0);
        childAt.setChecked(true);



        menu = new SlidingMenu(this);
        menu.setMenu(R.layout.menu);
        menu.setSecondaryMenu(R.layout.secondary_menu);
        menu.setMode(SlidingMenu.LEFT_RIGHT);
        menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        menu.setBehindOffset(200);
        menu.setRightMenuOffset(400);
        menu.setFadeDegree(0.0f);
        menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
        menu.setTouchmodeMarginThreshold(50);



        menu.setBackgroundRes(R.mipmap.sliding_bg);

        menu.setBehindCanvasTransformer(new SlidingMenu.CanvasTransformer() {
            @Override
            public void transformCanvas(Canvas canvas, float percentOpen) {
                float scale = (float) (percentOpen * 0.25 + 0.75);
                canvas.scale(scale, scale, -canvas.getWidth() / 2,
                        canvas.getHeight() / 2);
            }
        });

        menu.setAboveCanvasTransformer(new SlidingMenu.CanvasTransformer() {
            @Override
            public void transformCanvas(Canvas canvas, float percentOpen) {
                float scale = (float) (1 - percentOpen * 0.25);
                canvas.scale(scale, scale, 0, canvas.getHeight() / 2);
            }
        });


        LinearLayout collection = (LinearLayout) findViewById(R.id.collection);
        collection.setOnClickListener(this);

    }

    private long lastBackTime = 0;

    @Override
    public void onBackPressed() {
        long currentBackTime = System.currentTimeMillis();

        if (currentBackTime - lastBackTime < 2000){
            finish();
        }else {
            Toast.makeText(this,"再次点击退出程序!",Toast.LENGTH_SHORT).show();
        }

        lastBackTime = currentBackTime;
    }

    @Override
    protected void onStop() {
        super.onStop();
        mRequestQueue.cancelAll(this);
    }

    public void btnLeftMenuClick(View v){
        if (menu.isMenuShowing()){
            menu.toggle(true);
        }else {
            menu.showMenu(true);
        }
    }

    public void btnRightMenuClick(View v){
        if (menu.isSecondaryMenuShowing()){
            menu.toggle(true);
        }else {
            menu.showSecondaryMenu(true);
        }
    }


    //////////////////////
    ///ViewPager和RadioButton的联动

    private int currentPageIndex;

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTableLine.getLayoutParams();

        if (currentPageIndex == 0 && position == 0){
            lp.leftMargin = (int)(positionOffset * mScreen1_5 + currentPageIndex * mScreen1_5);

        }else if (currentPageIndex == 1 && position == 0){
            lp.leftMargin = (int)((positionOffset - 1) * mScreen1_5 + currentPageIndex * mScreen1_5);

        }else if (currentPageIndex == 1 && position == 1){
            lp.leftMargin = (int)(positionOffset * mScreen1_5 + currentPageIndex * mScreen1_5);

        }else if (currentPageIndex == 2 && position == 1){
            lp.leftMargin = (int)((positionOffset - 1) * mScreen1_5 + currentPageIndex * mScreen1_5);

        }else if (currentPageIndex == 2 && position == 2){
            lp.leftMargin = (int)(positionOffset * mScreen1_5 + currentPageIndex * mScreen1_5);

        }else if (currentPageIndex == 3 && position == 2){
            lp.leftMargin = (int)((positionOffset - 1) * mScreen1_5 + currentPageIndex * mScreen1_5);

        }else if (currentPageIndex == 3 && position == 3){
            lp.leftMargin = (int)(positionOffset * mScreen1_5 + currentPageIndex * mScreen1_5);

        }else if (currentPageIndex == 4 && position == 3){
            lp.leftMargin = (int)((positionOffset - 1) * mScreen1_5 + currentPageIndex * mScreen1_5);

        }

        mTableLine.setLayoutParams(lp);
    }
    @Override
    public void onPageSelected(int position) {

        View childAt = mRadioGroup.getChildAt(position);
        if (childAt instanceof RadioButton){
            RadioButton radioButton = (RadioButton) childAt;
            radioButton.setChecked(true);
        }


        currentPageIndex = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        int childCount = group.getChildCount();
        int position = -1;
        for (int i = 0; i < childCount; i++) {
            View childAt = group.getChildAt(i);
            if (childAt instanceof RadioButton){
                RadioButton radioButton = (RadioButton) childAt;
                if (radioButton.isChecked()){
                    position = i;
                    break;
                }
            }
        }
        if (position > -1) {
            mViewPager.setCurrentItem(position);
        }
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(this,"查看收藏!",Toast.LENGTH_SHORT).show();
    }
}
